package net.zhuike.novel.app.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.ListPopupWindow;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.j256.ormlite.stmt.query.In;
import com.luomi.lm.ad.ADType;
import com.luomi.lm.ad.Advertisement;
import com.luomi.lm.ad.DRAgent;
import com.luomi.lm.ad.IAdNativeSuccessBack;
import com.luomi.lm.ad.IAdSuccessBack;
import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.ZhuiKeApplication;
import net.zhuike.novel.app.bean.BookChapterBean;
import net.zhuike.novel.app.bean.BookRecordBean;
import net.zhuike.novel.app.bean.BookSit;
import net.zhuike.novel.app.bean.ChapterInfoBean;
import net.zhuike.novel.app.bean.ChapterRead;
import net.zhuike.novel.app.bean.CollBookBean;
import net.zhuike.novel.app.bean.SitBean;
import net.zhuike.novel.app.bean.local.BookRepository;
import net.zhuike.novel.app.bean.local.ReadSettingManager;
import net.zhuike.novel.app.bean.local.SitRepository;
import net.zhuike.novel.app.bean.support.BookMark;
import net.zhuike.novel.app.bean.support.DownloadMessage;
import net.zhuike.novel.app.bean.support.DownloadProgress;
import net.zhuike.novel.app.bean.support.DownloadQueue;
import net.zhuike.novel.app.bean.support.ReadTheme;
import net.zhuike.novel.app.bean.user.MenuModel;
import net.zhuike.novel.app.manager.CollectionsManager;
import net.zhuike.novel.app.manager.EventManager;
import net.zhuike.novel.app.manager.SettingManager;
import net.zhuike.novel.app.manager.ThemeManager;
import net.zhuike.novel.app.service.BookReadService;
import net.zhuike.novel.app.service.DownloadBService;
import net.zhuike.novel.app.service.UpdateBookChaterService;
import net.zhuike.novel.app.ui.adapter.ReadThemeAdapter;
import net.zhuike.novel.app.ui.adapter.TocListAdapter;
import net.zhuike.novel.app.ui.adapter.TocSourceListAdapter;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.AppUtils;
import net.zhuike.novel.app.ui.utils.BookManager;
import net.zhuike.novel.app.ui.utils.BrightnessUtils;
import net.zhuike.novel.app.ui.utils.FileUtils;
import net.zhuike.novel.app.ui.utils.FormatUtils;
import net.zhuike.novel.app.ui.utils.GlideLoadUtils;
import net.zhuike.novel.app.ui.utils.RxUtils;
import net.zhuike.novel.app.ui.utils.ScreenUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.SiteHelper;
import net.zhuike.novel.app.ui.utils.StringUtils;
import net.zhuike.novel.app.ui.utils.ToastUtils;
import net.zhuike.novel.app.ui.view.page.NetPageLoader;
import net.zhuike.novel.app.ui.view.page.PageLoader;
import net.zhuike.novel.app.ui.view.page.PageView;
import net.zhuike.novel.app.ui.view.page.TxtChapter;
import net.zhuike.novel.app.ui.view.readview.BaseReadView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import framework.common.baseui.UeBaseActivity;
import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;
import framework.log.LogUtils;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.functions.Action1;

import static android.R.attr.onClick;
import static android.view.View.VISIBLE;


/**
 * Created by wq on 2017/6/18.
 */
public class ReadActivity extends UeBaseActivity {
    protected CompositeDisposable mDisposable;
    public static final String EXTRA_IS_COLLECTED = "extra_is_collected";
    //注册 Brightness 的 uri
    private final Uri BRIGHTNESS_MODE_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
    private final Uri BRIGHTNESS_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
    private final Uri BRIGHTNESS_ADJ_URI =
            Settings.System.getUriFor("screen_auto_brightness_adj");

    private boolean isRegistered = false;
    @Bind(R.id.ivBack)
    ImageView mIvBack;
    @Bind(R.id.closeBtn)
    ImageView closeBtn;
    @Bind(R.id.closeAdBtn)
    ImageView closeAdBtn;
    @Bind(R.id.closeLastBtn)
    ImageView closeLastBtn;
    @Bind(R.id.tvBookReadSource)
    TextView mTvBookReadChangeSource;
    @Bind(R.id.tvBookMark)
    TextView tvBookMark;
    @Bind(R.id.flReadWidget)
    FrameLayout flReadWidget;
    @Bind(R.id.read_pv_page)
    PageView mPvPage;
    @Bind(R.id.tvBookReadTocTitle)
    TextView mTvBookReadTocTitle;
    @Bind(R.id.tvBookReadMode)
    ImageView mTvBookReadMode;
    @Bind(R.id.tvBookReadSettings)
    ImageView mTvBookReadSettings;
    @Bind(R.id.tvBookReadDownload)
    ImageView mTvBookReadDownload;
    @Bind(R.id.tvBookReadToc)
    ImageView mTvBookReadToc;
    @Bind(R.id.llBookReadTop)
    LinearLayout mLlBookReadTop;
    @Bind(R.id.llBookReadBottom)
    LinearLayout mLlBookReadBottom;
    @Bind(R.id.rlBookReadRoot)
    RelativeLayout mRlBookReadRoot;
    @Bind(R.id.tvDownloadProgress)
    TextView mTvDownloadProgress;

    @Bind(R.id.rlReadAaSet)
    LinearLayout rlReadAaSet;
    @Bind(R.id.ivBrightnessMinus)
    ImageView ivBrightnessMinus;
    @Bind(R.id.seekbarLightness)
    SeekBar seekbarLightness;
    @Bind(R.id.ivBrightnessPlus)
    ImageView ivBrightnessPlus;
    @Bind(R.id.tvFontsizeMinus)
    TextView tvFontsizeMinus;
    @Bind(R.id.seekbarFontSize)
    SeekBar seekbarFontSize;
    @Bind(R.id.tvFontsizePlus)
    TextView tvFontsizePlus;
    @Bind(R.id.ivLeftBtn)
    TextView ivLeftBtn;
    @Bind(R.id.ivRightBtn)
    TextView ivRightBtn;
    @Bind(R.id.classicPageLayout)
    LinearLayout classicPageLayout;
    @Bind(R.id.classicPage)
    TextView classicPageTx;
    @Bind(R.id.upDownPageLayout)
    LinearLayout upDownPageLayout;
    @Bind(R.id.upDownPage)
    TextView upDownPageTx;
    @Bind(R.id.bookPageLayout)
    LinearLayout bookPageLayout;
    @Bind(R.id.bookPage)
    TextView bookPageTx;
    @Bind(R.id.originalEditionLayout)
    LinearLayout originalEditionLayout;
    @Bind(R.id.originalEdition)
    TextView originalEditionTx;
    @Bind(R.id.compactPageLayout)
    LinearLayout compactPageLayout;
    @Bind(R.id.compactPage)
    TextView compactPageTx;
    @Bind(R.id.moderatePageLayout)
    LinearLayout moderatePageLayout;
    @Bind(R.id.moderatePage)
    TextView moderatePageTx;
    @Bind(R.id.loosePageLayout)
    LinearLayout loosePageLayout;
    @Bind(R.id.loosePage)
    TextView loosePageTx;
    @Bind(R.id.defaultSizeLayout)
    LinearLayout defaultSizeLayout;
    @Bind(R.id.defaultSize)
    TextView defaultSizeTx;
    @Bind(R.id.addFontLayout)
    LinearLayout addFontLayout;
    @Bind(R.id.addFont)
    TextView addFontTx;
    @Bind(R.id.tvFonts)
    TextView tvFonts;
    @Bind(R.id.cbVolume)
    CheckBox cbVolume;
    @Bind(R.id.cbAutoBrightness)
    CheckBox cbAutoBrightness;
    @Bind(R.id.gvTheme)
    GridView gvTheme;
    @Bind(R.id.mill_layout)
    LinearLayout mill_layout;
    @Bind(R.id.tips)
    LinearLayout tips;
    @Bind(R.id.adLayout)
    RelativeLayout adLayout;
    @Bind(R.id.adLastLayout)
    RelativeLayout adLastLayout;
    @Bind(R.id.last_layout)
    LinearLayout last_layout;
    @Bind(R.id.iv_ad_image)
    ImageView iv_ad_image;
    @Bind(R.id.adText)
    TextView adText;
    private View decodeView;
    RelativeLayout adBooTomLayout;
    private List<BookSit.Chapters> mChapterSitList = new ArrayList<>();
    private List<BookSit.Chapters> mChapterSitLists = new ArrayList<>();
    private List<BookChapterBean> mChapterList = new ArrayList<>();
    private ListPopupWindow mTocListPopupWindow;
    private TocSourceListAdapter mTocListAdapter;
    private ReadSettingManager mSettingManager;
    private OkHttpClient mOkHttpClient;
    List<MenuModel> list = new ArrayList<MenuModel>();
    private int currentChapter = 1;
    String contentRegex = "";
    String chapterContentReplaceRules = "";
    /**
     * 是否开始阅读章节
     **/
    private boolean startRead = false;
    private Subscription mChapterSub;
    private Handler handler = null;
    private BaseReadView mPageWidget;
    private int curTheme = -1;
    private List<ReadTheme> themes;
    private ReadThemeAdapter gvAdapter;
    private Receiver receiver = new Receiver();
    private IntentFilter intentFilter = new IntentFilter();
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    public static final String INTENT_BEAN = "recommendBooksBean";
    public static final String INTENT_SD = "isFromSD";
    private CollBookBean recommendBooks;
    private String bookId;
    private String contentUrl;
    private boolean isAutoLightness = false; // 记录其他页面是否自动调整亮度
    private boolean isFromSD = false;
    private Context mContext;
    private boolean isNightMode = false;
    private PageLoader mPageLoader;
    private SiteHelper helper;
    private int mTextSize;
    private String aid = "";
    private ProgressDialog mProgressDialog;
    String loadUrl;
    String currentChapterLink = "";
    String chapterTitle = "";
    List<ChapterInfoBean> chapterInfos = null;
    ArrayDeque<String> titles = null;
    SitBean bean;
    int height;
    int width;
    //控制屏幕常亮
    private PowerManager.WakeLock mWakeLock;
    Advertisement advertisement;
    // 接收电池信息和时间更新的广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
                int level = intent.getIntExtra("level", 0);
                mPageLoader.updateBattery(level);
            }
            //监听分钟的变化
            else if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mPageLoader.updateTime();
            }
        }
    };
    //亮度调节监听
    //由于亮度调节没有 Broadcast 而是直接修改 ContentProvider 的。所以需要创建一个 Observer 来监听 ContentProvider 的变化情况。
    private ContentObserver mBrightObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            onChange(selfChange, null);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange);

            //判断当前是否跟随屏幕亮度，如果不是则返回
            if (selfChange || !cbAutoBrightness.isChecked()) return;

            //如果系统亮度改变，则修改当前 Activity 亮度
            if (BRIGHTNESS_MODE_URI.equals(uri)) {
            } else if (BRIGHTNESS_URI.equals(uri) && !BrightnessUtils.isAutoBrightness(ReadActivity.this)) {
                BrightnessUtils.setBrightness(ReadActivity.this,BrightnessUtils.getScreenBrightness(ReadActivity.this));
            } else if (BRIGHTNESS_ADJ_URI.equals(uri) && BrightnessUtils.isAutoBrightness(ReadActivity.this)) {
                BrightnessUtils.setBrightness(ReadActivity.this,BrightnessUtils.getScreenBrightness(ReadActivity.this));
            } else {
            }
        }
    };
    //添加收藏需要，所以跳转的时候传递整个实体类
    public static void startActivity(Context context, CollBookBean recommendBooks) {
        startActivity(context, recommendBooks, false);
    }

    public static void startActivity(Context context, CollBookBean recommendBooks, boolean isFromSD) {
        context.startActivity(new Intent(context, ReadActivity.class)
                .putExtra(INTENT_BEAN, recommendBooks)
                .putExtra(INTENT_SD, isFromSD));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_read);
        handler = new Handler();
        hiddenFooter();
        hiddenHeader();
        mContext = this;
        adBooTomLayout=(RelativeLayout)findViewById(R.id.adBooTomLayout) ;
        //获取页面加载器
        getHitHelper();
        initDatas();
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);

         width = wm.getDefaultDisplay().getWidth();
         height = wm.getDefaultDisplay().getHeight();
    }

    public void initDatas() {
        mSettingManager = ReadSettingManager.getInstance();
        recommendBooks = getIntent().getParcelableExtra(INTENT_BEAN);
        bookId = recommendBooks.getId();
        if (getIntent().getStringExtra("aid") != null) {
            aid = getIntent().getStringExtra("aid");
        } else {
            aid = recommendBooks.getAid();
        }
        Intent regIntent = new Intent(this, UpdateBookChaterService.class);
        regIntent.putExtra("booId",bookId);
        regIntent.putExtra("aid",aid);
        startService(regIntent);
        getMixAToc(bookId);
        mPageLoader = mPvPage.getPageLoader(recommendBooks.isLocal());
        mTextSize = mSettingManager.getTextSize();
        tvFonts.setText(mTextSize+"");
        isFromSD = getIntent().getBooleanExtra(INTENT_SD, false);
        isNightMode = ReadSettingManager.getInstance().isNightMode();
         bean= SitRepository.getInstance().getSit(bookId);
        if(bean!=null) {
            contentUrl = bean.getUrl();
            loadUrl = bean.getLoadUrl();
        }
        toggleNightMode();
        EventBus.getDefault().register(this);
        mTvBookReadTocTitle.setText(recommendBooks.getName());

        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mReceiver, intentFilter);
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        //延迟1秒刷新书架
                        EventManager.refreshCollectionList();
                    }
                });
        configViews();
        if(!(SharedPreferencesUtil.getInstance().getString("chapterBottom")==null||SharedPreferencesUtil.getInstance().getString("chapterBottom").equals(""))){
            if(SharedPreferencesUtil.getInstance().getString("chapterBottom").equals("true")){
                DRAgent.getInstance().getOpenNativeAd(ReadActivity.this, ADType.MESSAGE_BIG_IMG, new IAdNativeSuccessBack() {
                    @Override
                    public void onSuccess(final Advertisement advertisement) {
                        // TODO Auto-generated method stub
                        System.out.println(">>>>>>>>>>>>原生广告信息:" + advertisement.toString());
                        Message msg=new Message();
                        msg.obj=advertisement;
                        handlerss.sendMessage(msg);
                    }

                    @Override
                    public void onFailed(String infoStr) {
                        // TODO Auto-generated method stub
                        System.out.println(">>>>>>>>>>infoStr:"+infoStr);

                    }
                });
//                DRAgent.getInstance().getOpenView(mContext, ADType.MESSAGE_IMGS, true, new IAdSuccessBack() {
//
//                    @Override
//                    public void onError(final String result) {
//
//                    }
//
//                    @Override
//                    public void onClick(String result) {
//                        // TODO Auto-generated method stub
//                        // TODO Auto-generated method stub
//
//                    }
//
//                    @Override
//                    public void OnSuccess(String result) {
//                        // TODO Auto-generated method stub
//
//                        // TODO Auto-generated method stub
//
//                    }
//
//                    @Override
//                    public void OnLoadAd(View view) {
//                        // TODO Auto-generated method stub
//                        adBooTomLayout.setVisibility(View.VISIBLE);
//                        bannerLayout.addView(view);
//                    }
//                });
            }else{
                adBooTomLayout.setVisibility(View.GONE);
            }
        }else {
            adBooTomLayout.setVisibility(View.GONE);
        }

    }

    public void configViews() {
        decodeView = getWindow().getDecorView();
        initAASet();
        initPagerWidget();
        initClick();
        processLogic();
    }
    private void initAASet() {
        seekbarFontSize.setMax(10);
        int fontSizePx = SettingManager.getInstance().getReadFontSize();
        int progress = (int) ((ScreenUtils.pxToDpInt(fontSizePx) - 12) / 1.7f);
        seekbarFontSize.setProgress(progress);
        seekbarFontSize.setOnSeekBarChangeListener(new SeekBarChangeListener());
        seekbarLightness.setMax(100);
        seekbarLightness.setOnSeekBarChangeListener(new SeekBarChangeListener());
        seekbarLightness.setProgress(SettingManager.getInstance().getReadBrightness());
        isAutoLightness = mSettingManager.isBrightnessAuto();
        cbVolume.setChecked(SettingManager.getInstance().isVolumeFlipEnable());
        cbVolume.setOnCheckedChangeListener(new ChechBoxChangeListener());

        cbAutoBrightness.setChecked(isAutoLightness);
        cbAutoBrightness.setOnCheckedChangeListener(new ChechBoxChangeListener());

        gvAdapter = new ReadThemeAdapter(this, (themes = ThemeManager.getReaderThemeData()));
        gvTheme.setAdapter(gvAdapter);
        gvTheme.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPageLoader.setBgColor(position);
            }
        });


    }

    private void initPagerWidget() {
        registerReceiver(receiver, intentFilter);
        //获取页面加载器
        mPageLoader = mPvPage.getPageLoader(recommendBooks.isLocal());
        //设置当前Activity的Bright
        if (ReadSettingManager.getInstance().isBrightnessAuto()) {
            BrightnessUtils.setBrightness(this, BrightnessUtils.getScreenBrightness(this));
        } else {
            BrightnessUtils.setBrightness(this, ReadSettingManager.getInstance().getBrightness());
        }
        int lines=0;
        if(!(SharedPreferencesUtil.getInstance().getString("line")==null||SharedPreferencesUtil.getInstance().getString("line").equals(""))){
            lines=Integer.parseInt(SharedPreferencesUtil.getInstance().getString("line"));
        }
        if(lines==0){
            originalEditionLayout.setBackgroundResource(R.drawable.shape_left_press_button);
            originalEditionTx.setTextColor(Color.parseColor("#ffffff"));
            compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            compactPageTx.setTextColor(Color.parseColor("#1089DC"));
            moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
            loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
            loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        }else if(lines==1){
            originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
            originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
            compactPageLayout.setBackgroundResource(R.drawable.shape_middle_press_button);
            compactPageTx.setTextColor(Color.parseColor("#ffffff"));
            moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
            loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
            loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        }else if(lines==2){
            originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
            originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
            compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            compactPageTx.setTextColor(Color.parseColor("#1089DC"));
            moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_press_button);
            moderatePageTx.setTextColor(Color.parseColor("#ffffff"));
            loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
            loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        }else{
            originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
            originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
            compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            compactPageTx.setTextColor(Color.parseColor("#1089DC"));
            moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
            moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
            loosePageLayout.setBackgroundResource(R.drawable.shape_right_press_button);
            loosePageTx.setTextColor(Color.parseColor("#ffffff"));
        }
        //初始化屏幕常亮类
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "keep bright");
    }



    public void netError(int chapter) {
        hideDialog();//防止因为网络问题而出现dialog不消失
        if (Math.abs(chapter - currentChapter) <= 1) {
            ToastUtils.showToast(R.string.net_error);
        }
    }

    private synchronized void hideReadBar() {
        gone(mTvDownloadProgress, rlReadAaSet);
        gone(mLlBookReadBottom);
        gone(mLlBookReadTop);
        // decodeView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }


    @OnClick(R.id.ivBack)
    public void onClickIntroduce() {

        finish();

    }
    @OnClick(R.id.closeBtn)
    public void onClickClose(){
        adLayout.setVisibility(View.GONE);
    }
    @OnClick(R.id.closeAdBtn)
    public void onClickAdClose(){
        adBooTomLayout.setVisibility(View.GONE);
    }
    @OnClick(R.id.closeLastBtn)
    public void onClickAdLstClose(){
        adLastLayout.setVisibility(View.GONE);
    }
    @OnClick(R.id.tvBookReadSource)
    public void onClickSource() {
        BookSourceActivity.start(this, mChapterSitLists, 1,bookId);
    }

    /***************Bottom Bar*****************/

    @OnClick(R.id.tvBookReadMode)
    public void onClickChangeMode() { // 日/夜间模式切换
        gone(rlReadAaSet);

        if (isNightMode) {
            isNightMode = false;
        } else {
            isNightMode = true;
        }
        mPageLoader.setNightMode(isNightMode);
        toggleNightMode();
    }
    private void toggleNightMode() {
        if (isNightMode) {
            mTvBookReadMode.setImageResource(R.drawable.selector_mode_day_btn);
        } else {
            mTvBookReadMode.setImageResource(R.drawable.selector_mode_night_btn);
        }
    }

    @OnClick(R.id.tvBookReadSettings)
    public void setting() {
        setMenu(true);
    }

    /***目录***/
    @OnClick(R.id.tvBookReadToc)
    public void onClickToc() {
        toggleMenu(true);
        Intent in = new Intent(ReadActivity.this, ReadMenuActivity.class);
        in.putExtra("recommendBooksBean", recommendBooks);
        in.putExtra("mChapterList", (Serializable) mChapterList);
        in.putExtra("type", "2");
        startActivityForResult(in, 3);
    }

    /***************Setting 翻页方式*****************/
    @OnClick(R.id.classicPageLayout)
    public void onClickPage() {
        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE, 1);
        classicPageLayout.setBackgroundResource(R.drawable.shape_left_press_button);
        classicPageTx.setTextColor(Color.parseColor("#ffffff"));
        upDownPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        upDownPageTx.setTextColor(Color.parseColor("#1089DC"));
        bookPageLayout.setBackgroundResource(R.drawable.shape_right_button);
        bookPageTx.setTextColor(Color.parseColor("#1089DC"));
        mPageLoader.setPageMode(PageView.PAGE_MODE_SIMULATION);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    @OnClick(R.id.upDownPageLayout)
    public void onClickUpDownPage() {
        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE, 1);
        classicPageLayout.setBackgroundResource(R.drawable.shape_left_button);
        classicPageTx.setTextColor(Color.parseColor("#1089DC"));
        upDownPageLayout.setBackgroundResource(R.drawable.shape_middle_press_button);
        upDownPageTx.setTextColor(Color.parseColor("#ffffff"));
        bookPageLayout.setBackgroundResource(R.drawable.shape_right_button);
        bookPageTx.setTextColor(Color.parseColor("#1089DC"));
        mPageLoader.setPageMode(PageView.PAGE_MODE_COVER);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    @OnClick(R.id.bookPageLayout)
    public void onClickBookPageLayout() {
        SharedPreferencesUtil.getInstance().putInt(Constant.FLIP_STYLE, 0);
        classicPageLayout.setBackgroundResource(R.drawable.shape_left_button);
        classicPageTx.setTextColor(Color.parseColor("#1089DC"));
        upDownPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        upDownPageTx.setTextColor(Color.parseColor("#1089DC"));
        bookPageLayout.setBackgroundResource(R.drawable.shape_right_press_button);
        bookPageTx.setTextColor(Color.parseColor("#ffffff"));
        mPageLoader.setPageMode(PageView.PAGE_MODE_SLIDE);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    /***************Setting 段落方式*****************/
    @OnClick(R.id.originalEditionLayout)//原版
    public void onClickOriginalEdition() {
        originalEditionLayout.setBackgroundResource(R.drawable.shape_left_press_button);
        originalEditionTx.setTextColor(Color.parseColor("#ffffff"));
        compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        compactPageTx.setTextColor(Color.parseColor("#1089DC"));
        moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
        SharedPreferencesUtil.getInstance().putString("line","0");
        loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
        loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        mPageLoader.changeLines(0,0);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    @OnClick(R.id.compactPageLayout)//紧凑
    public void onClickUpCompactPageLayout() {
        originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
        originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
        compactPageLayout.setBackgroundResource(R.drawable.shape_middle_press_button);
        compactPageTx.setTextColor(Color.parseColor("#ffffff"));
        moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
        loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
        loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        SharedPreferencesUtil.getInstance().putString("line","1");
        int num=1;
        if(!(SharedPreferencesUtil.getInstance().getString("spacing1")==null||SharedPreferencesUtil.getInstance().getString("spacing1").equals(""))){
           String []str=SharedPreferencesUtil.getInstance().getString("spacing1").split(",");
            num= Integer.parseInt(str[2]);
        }
        mPageLoader.changeLines(1,num);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    @OnClick(R.id.moderatePageLayout)//适中
    public void onClickModeratePageLayout() {
        originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
        originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
        compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        compactPageTx.setTextColor(Color.parseColor("#1089DC"));
        moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_press_button);
        moderatePageTx.setTextColor(Color.parseColor("#ffffff"));
        loosePageLayout.setBackgroundResource(R.drawable.shape_right_button);
        loosePageTx.setTextColor(Color.parseColor("#1089DC"));
        SharedPreferencesUtil.getInstance().putString("line","2");
        int num=2;
        if(!(SharedPreferencesUtil.getInstance().getString("spacing2")==null||SharedPreferencesUtil.getInstance().getString("spacing2").equals(""))){
            String []str=SharedPreferencesUtil.getInstance().getString("spacing2").split(",");
            num= Integer.parseInt(str[2]);
        }
        mPageLoader.changeLines(2,num);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    @OnClick(R.id.loosePageLayout)//松散
    public void onClickLoosePageLayout() {
        originalEditionLayout.setBackgroundResource(R.drawable.shape_left_button);
        originalEditionTx.setTextColor(Color.parseColor("#1089DC"));
        compactPageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        compactPageTx.setTextColor(Color.parseColor("#1089DC"));
        moderatePageLayout.setBackgroundResource(R.drawable.shape_middle_button);
        moderatePageTx.setTextColor(Color.parseColor("#1089DC"));
        loosePageLayout.setBackgroundResource(R.drawable.shape_right_press_button);
        loosePageTx.setTextColor(Color.parseColor("#ffffff"));
        int num=3;
        SharedPreferencesUtil.getInstance().putString("line","3");
        if(!(SharedPreferencesUtil.getInstance().getString("spacing3")==null||SharedPreferencesUtil.getInstance().getString("spacing3").equals(""))){
            String []str=SharedPreferencesUtil.getInstance().getString("spacing3").split(",");
            num= Integer.parseInt(str[2]);
        }
        mPageLoader.changeLines(3,num);
        mLlBookReadBottom.setVisibility(View.GONE);
        mLlBookReadTop.setVisibility(View.GONE);
        rlReadAaSet.setVisibility(View.GONE);
    }

    /***************Setting 选择字体*****************/
    @OnClick(R.id.defaultSizeLayout)
    public void onClickDefaultSizeLayout() {
        defaultSizeLayout.setBackgroundResource(R.drawable.shape_left_press_button);
        defaultSizeTx.setTextColor(Color.parseColor("#ffffff"));
        addFontLayout.setBackgroundResource(R.drawable.shape_right_button);
        addFontTx.setTextColor(Color.parseColor("#1089DC"));
        mSettingManager.setTypeface("");
        mPageLoader.setTextTff("");
        toggleMenu(true);
    }

    @OnClick(R.id.addFontLayout)
    public void onClickAddFontLayout() {
        defaultSizeLayout.setBackgroundResource(R.drawable.shape_left_button);
        defaultSizeTx.setTextColor(Color.parseColor("#1089DC"));
        addFontLayout.setBackgroundResource(R.drawable.shape_right_press_button);
        addFontTx.setTextColor(Color.parseColor("#ffffff"));
        toggleMenu(true);
        Intent intent = new Intent(ReadActivity.this, FontActivity.class);
        startActivityForResult(intent, 10098);
    }

    /***************Setting Menu*****************/

    @OnClick(R.id.ivBrightnessMinus)
    public void brightnessMinus() {
        int curBrightness = SettingManager.getInstance().getReadBrightness();
        if (curBrightness > 2 && !SettingManager.getInstance().isAutoBrightness()) {
            seekbarLightness.setProgress((curBrightness = curBrightness - 2));
            BrightnessUtils.setBrightness(ReadActivity.this, curBrightness - 2);
            ReadSettingManager.getInstance().setBrightness(curBrightness - 2);
        }
    }

    @OnClick(R.id.ivBrightnessPlus)
    public void brightnessPlus() {
        int curBrightness = SettingManager.getInstance().getReadBrightness();
        if (curBrightness < 99 && !SettingManager.getInstance().isAutoBrightness()) {
            seekbarLightness.setProgress((curBrightness = curBrightness + 2));
            BrightnessUtils.setBrightness(ReadActivity.this, curBrightness + 2);
            ReadSettingManager.getInstance().setBrightness(curBrightness + 2);
        }
    }

    @OnClick(R.id.tvFontsizeMinus)
    public void fontsizeMinus() {
        int num=1;
        if(!(SharedPreferencesUtil.getInstance().getString("fontSizeSetp")==null||SharedPreferencesUtil.getInstance().getString("fontSizeSetp").equals("")))
        {
            num=Integer.parseInt(SharedPreferencesUtil.getInstance().getString("fontSizeSetp"));
        }
        int fontSize = Integer.valueOf(tvFonts.getText().toString())-num;
        if (fontSize < 0) return;
        tvFonts.setText(fontSize+"");
        mPageLoader.setTextSize(fontSize);
    }

    @OnClick(R.id.tvFontsizePlus)
    public void fontsizePlus() {
        int num=1;
        if(!(SharedPreferencesUtil.getInstance().getString("fontSizeSetp")==null||SharedPreferencesUtil.getInstance().getString("fontSizeSetp").equals("")))
        {
            num=Integer.parseInt(SharedPreferencesUtil.getInstance().getString("fontSizeSetp"));
        }
        int fontSize = Integer.valueOf(tvFonts.getText().toString())+num;
        tvFonts.setText(fontSize+"");
        mPageLoader.setTextSize(fontSize);
    }



    /***************Book Mark*****************/

    @OnClick(R.id.tvBookMark)
    public void addBookMark() {
        mPageLoader.saveRecord();
        BookRecordBean mBookRecords = BookRepository.getInstance()
                .getBookRecord(bookId);
        BookMark mark = new BookMark();
        mark.desc = mPageLoader.getHeadLine();
        if (mBookRecords != null) {
            mark.chapter = mBookRecords.getChapter();
            mark.startPos = mBookRecords.getPagePos();
            if (mark.chapter >= 1 && mark.chapter <= mChapterList.size()) {
                mark.title = mChapterList.get(mark.chapter).getTitle();
            }else {
                if(recommendBooks!=null){
                    mark.title=recommendBooks.getBookChapterList().get(mark.chapter).getTitle();
                }
            }
        }
        if (SettingManager.getInstance().ifBookMark(bookId, mark)) {
            Drawable drawable = ContextCompat.getDrawable(mContext, R.mipmap.ic_mark_hover);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvBookMark.setCompoundDrawables(drawable, null, null, null);
            SettingManager.getInstance().addBookMark(bookId,mark);
            ToastUtils.showSingleToast("添加书签成功");

        } else {
            SettingManager.getInstance().revoeBookMarks(bookId,mark);
            ToastUtils.showSingleToast("书签已移除");
            Drawable drawable = ContextCompat.getDrawable(mContext, R.mipmap.ic_menu_bookmark);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvBookMark.setCompoundDrawables(drawable, null, null, null);
        }
    }

    @OnClick(R.id.ivLeftBtn)
    public void upPage() {
        mPageLoader.skipPreChapter();
        toggleMenu(true);
    }

    @OnClick(R.id.ivRightBtn)
    public void nextPage() {
        mPageLoader.skipNextChapter();
        toggleMenu(true);
    }

    /***************Event*****************/

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showDownProgress(DownloadProgress progress) {
        if (bookId.equals(progress.bookId)) {
            if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
                toggleMenu(true);
                // 如果之前缓存过，就给提示
                mTvDownloadProgress.setText(progress.message);
            } else {
                gone(mTvDownloadProgress);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadMessage(final DownloadMessage msg) {
        if (isVisible(mLlBookReadBottom)) { // 如果工具栏显示，则进度条也显示
            if (bookId.equals(msg.bookId)) {
                toggleMenu(true);
                mTvDownloadProgress.setText(msg.message);
                if (msg.isComplete) {
                    mTvDownloadProgress.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            gone(mTvDownloadProgress);
                        }
                    }, 2500);
                }
            }
        }
    }

    /**
     * 显示加入书架对话框
     *
     * @param bean
     */
    private void showJoinBookShelfDialog(final CollBookBean bean) {
        if (!bean.isLocal() && !isFromSD) {
            new AlertDialog.Builder(mContext)
                    .setTitle(getString(R.string.book_read_add_book))
                    .setMessage(getString(R.string.book_read_would_you_like_to_add_this_to_the_book_shelf))
                    .setPositiveButton(getString(R.string.book_read_join_the_book_shelf), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            isFromSD = true;
                            bean.setBookChapters(bean.getBookChapters());
                            bean.setLastestUpdateTime(StringUtils.
                                    dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));
                            BookRepository.getInstance()
                                    .saveCollBookWithAsync(bean);
                            isFromSD = true;
                            finish();
                        }
                    })
                    .setNegativeButton(getString(R.string.book_read_not), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .create()
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    BookSit.Chapters bookSource = (BookSit.Chapters) data.getSerializableExtra("source");
                    showDialog();
                    contentUrl = UeHttpUrl.getChapterRead()+bookSource.domain;
                    currentChapter = 1;
                    loadUrl = bookSource.url;
                    getChapter(contentUrl, bookSource.url, currentChapter);
                    hideReadBar();
                }
                break;
            case 2:
                break;
            case 3:
                if (data != null) {
                    if (data.getStringExtra("type") != null) {
                        if (data.getStringExtra("type").equals("2")) {
                            BookMark mark = (BookMark) data.getSerializableExtra("source");
                            mPageLoader.skipToChapter(mark.chapter);
                            hideReadBar();
                        } else {
                            if (recommendBooks.isLocal()) {
                                currentChapter = Integer.parseInt(data.getStringExtra("currentChapter"));
                                mPageLoader.skipToChapter(currentChapter);
                            } else {
                                bookId = data.getStringExtra("bookId");
                                currentChapterLink = data.getStringExtra("currentChapterLink");
                                chapterTitle = data.getStringExtra("title");
                                currentChapter = Integer.parseInt(data.getStringExtra("currentChapter"));
                                if(BookManager
                                        .isChapterCached(bookId,chapterTitle)){
                                    mPageLoader.skipToChapter(currentChapter);
                                }else {
                                    if (recommendBooks.getBookChapters() != null) {
                                        nextChapterRead(bookId);
                                    } else {
                                        Disposable disposable = BookRepository.getInstance()
                                                .getBookChaptersInRx(bookId)
                                                .compose(RxUtils::toSimpleSingle)
                                                .subscribe(
                                                        (bookChapterBeen, throwable) -> {
                                                            if (bookChapterBeen.size() > 0) {
                                                                recommendBooks.setBookChapters(bookChapterBeen);
                                                                nextChapterRead(bookId);
                                                            }
                                                        }
                                                );
                                        if (mDisposable == null) {
                                            mDisposable = new CompositeDisposable();
                                        }
                                        mDisposable.add(disposable);
                                    }
                                }
                            }
                        }
                    }
                }
                break;
            case 10098:
                if (data != null) {
                    String path = data.getStringExtra("path");
                    mPageLoader.setTextTff(path);
                }
                mLlBookReadBottom.setVisibility(View.GONE);
                mLlBookReadTop.setVisibility(View.GONE);
                rlReadAaSet.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (!recommendBooks.isLocal() && !isFromSD) {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("加入书架")
                    .setMessage("喜欢本书就加入书架吧")
                    .setPositiveButton("确定", (dialog, which) -> {
                        //设置为已收藏
                        isFromSD = true;
                        //设置BookChapter
                        recommendBooks.setBookChapters(recommendBooks.getBookChapters());
                        //设置阅读时间
                        recommendBooks.setLastestUpdateTime(StringUtils.
                                dateConvert(System.currentTimeMillis(), Constant.FORMAT_BOOK_DATE));

                        BookRepository.getInstance()
                                .saveCollBookWithAsync(recommendBooks);
                        //mPresenter.addToBookShelf(bean, mCollBookBean);
                        //mTvChase.setText(getResources().getString(R.string.nb_book_detail_give_up));
                        isFromSD = true;
                        exit();
                    })
                    .setNegativeButton("取消", (dialog, which) -> {
                        exit();
                    }).create();
            alertDialog.show();
        } else {
            exit();
        }
    }

    //退出
    private void exit() {
        //返回给BookDetail。
        Intent result = new Intent();
        result.putExtra(BookDetailActivity.RESULT_IS_COLLECTED, isFromSD);
        setResult(Activity.RESULT_OK, result);
        //退出
        super.onBackPressed();
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                mPageWidget.nextPage();
                return true;// 防止翻页有声音
            }
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (SettingManager.getInstance().isVolumeFlipEnable()) {
                //mPageWidget.prePage();
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mTtsPlayer.getPlayerState() == TTSCommonPlayer.PLAYER_STATE_PLAYING)
//            mTtsPlayer.stop();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        stopService(new
                Intent(this,
                UpdateBookChaterService.class));
        EventManager.refreshCollectionIcon();
        EventManager.refreshCollectionList();
        EventBus.getDefault().unregister(this);
        try {
            unregisterReceiver(mReceiver);
            unregisterReceiver(receiver);
            unregisterReceiver(mReceiver);
            mPageLoader.closeBook();
        } catch (Exception e) {
            LogUtils.e("Receiver not registered");
        }
        // 观察内存泄漏情况
        //  ReaderApplication.getRefWatcher(this).watch(this);
    }

    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (seekBar.getId() == seekbarFontSize.getId() && fromUser) {
                calcFontSize(progress);
            } else if (seekBar.getId() == seekbarLightness.getId() && fromUser
                    ) { // 非自动调节模式下 才可调整屏幕亮度
                if (cbAutoBrightness.isChecked()) {
                    cbAutoBrightness.setChecked(false);
                }
                BrightnessUtils.setBrightness(ReadActivity.this, progress);
                //设置进度
                ReadSettingManager.getInstance().setBrightness(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    private class ChechBoxChangeListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.getId() == cbVolume.getId()) {
                SettingManager.getInstance().saveVolumeFlipEnable(isChecked);
            } else if (buttonView.getId() == cbAutoBrightness.getId()) {
                if (isChecked){
                    //获取屏幕的亮度
                    BrightnessUtils.setBrightness(ReadActivity.this,BrightnessUtils.getScreenBrightness(ReadActivity.this));
                }
                else {
                    //获取进度条的亮度
                    BrightnessUtils.setBrightness(ReadActivity.this,seekbarLightness.getProgress());
                }
                ReadSettingManager.getInstance().setAutoBrightness(isChecked);
            }
        }
    }

    class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (mPageWidget != null) {
                if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                    int level = intent.getIntExtra("level", 0);
                    mPageWidget.setBattery(100 - level);
                } else if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                    mPageWidget.setTime(sdf.format(new Date()));
                }
            }
        }
    }

    private void calcFontSize(int progress) {
        // progress range 1 - 10
        mPageLoader.setTextSize(mTextSize);
    }

    public void getMixAToc(String bookId) {
        BookReadService.getBookMixAToc(mContext, bookId, new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                tips.setVisibility(View.GONE);
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;
                    mChapterSitLists.clear();
                    mChapterSitList.clear();
                    if (list != null) {
                        mChapterSitList.addAll(list);
                        for( int i=0;i<mChapterSitList.size();i++) {
                            loadUrl=mChapterSitList.get(i).url;

                            BookSit.Chapters sit=mChapterSitList.get(i);
                            try {
                                mOkHttpClient = new OkHttpClient.Builder()
                                        .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                        .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                        .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                        .retryOnConnectionFailure(true)             //是否自动重连
                                        .build();
                                final Request request = new Request.Builder()
                                        .url(UeHttpUrl.getChapterRead()+mChapterSitList.get(i).domain)
                                        .get()
                                        .build();
                                Call call = mOkHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {

                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String str = response.body().string();
                                        String headers[] = null;
                                        try {
                                            JSONObject restr = JSONObject.parseObject(str);
                                            String name=restr.getString("name");
                                            sit.name=name;
                                            mChapterSitLists.add(sit);
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                });
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                if(errorCode==-1) {
                    Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void getChapterRead(String bookId, List<TxtChapter> bookChapters, TxtChapter bookChapter) {
        chapterInfos = new ArrayList<>(bookChapters.size());
        titles = new ArrayDeque<>(bookChapters.size());
            try {

                if (helper != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Map<String, Object> context2 = new HashMap<String, Object>();
                                context2.put("aid", aid);
                                context2 = helper.executeChapter(context2, bookChapter.getLink());
                                int i = 0;
                                while (true) {
                                    String body = "";
                                    if (context2.get("content") != null) {
                                        if (mProgressDialog != null) {
                                            mProgressDialog.dismiss();
                                        }
                                        if (context2.get("content").getClass() == JSONObject.class) {
                                            JSONObject contentJson = (JSONObject) context2.get("content");
                                            body = contentJson.getString("text");
                                        } else {
                                            Object content = (String) context2.get("content");
                                            body = content.toString();
                                        }
                                        ChapterInfoBean infoBean = new ChapterInfoBean();
                                        if (!body.equals("")) {
                                            infoBean.setBody(body);
                                        }
                                        chapterInfos.add(infoBean);
                                        titles.add(bookChapter.getTitle());
                                        String title = titles.poll();
                                        BookRepository.getInstance().saveChapterInfo(
                                                bookId, title, infoBean.getBody()
                                        );
                                        i = 0;
                                        handler.post(runnableUis);
                                        break;
                                    } else {
                                        Thread.sleep(1000);
                                        i++;
                                    }
                                    if (i == 5) {
                                        handler.post(runnableUi);
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();


                } else {
                    BookReadService.getBookMixAToc(mContext, bookId, new ResponseCallback<BookSit>() {
                        @Override
                        public void onSuccess(BookSit mixToc) {
                            tips.setVisibility(View.GONE);
                            if (mixToc != null) {
                                List<BookSit.Chapters> list = mixToc.mulus;
                                mChapterSitList.clear();
                                if (list != null) {
                                    mChapterSitList.addAll(list);

                                    if (mChapterSitList.size() > 0) {
                                        contentUrl =bean.getUrl();
                                        try {
                                            mOkHttpClient = new OkHttpClient.Builder()
                                                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                                    .retryOnConnectionFailure(true)             //是否自动重连
                                                    .build();
                                            final Request request = new Request.Builder()
                                                    .url(contentUrl)
                                                    .get()
                                                    .build();
                                            Call call = mOkHttpClient.newCall(request);
                                            call.enqueue(new Callback() {
                                                @Override
                                                public void onFailure(Call call, IOException e) {

                                                }

                                                @Override
                                                public void onResponse(Call call, Response response) throws IOException {
                                                    String str = response.body().string();
                                                    String headers[] = null;
                                                    try {
                                                        JSONObject restr = JSONObject.parseObject(str);
                                                        if (restr.get("failed") != null) {
                                                            handler.post(runnableUi);
                                                        } else {
                                                            helper = new SiteHelper(restr);
                                                            new Thread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    try {
                                                                        Map<String, Object> context2 = new HashMap<String, Object>();
                                                                        context2.put("aid", aid);
                                                                        context2 = helper.executeChapter(context2, bookChapter.getLink());
                                                                        int i = 0;
                                                                        while (true) {
                                                                            String body = "";
                                                                            if (context2.get("content") != null) {
                                                                                if (mProgressDialog != null) {
                                                                                    mProgressDialog.dismiss();
                                                                                }
                                                                                if (context2.get("content").getClass() == JSONObject.class) {
                                                                                    JSONObject contentJson = (JSONObject) context2.get("content");
                                                                                    body = contentJson.getString("text");
                                                                                } else {
                                                                                    Object content = (String) context2.get("content");
                                                                                    body = content.toString();
                                                                                }
                                                                                ChapterInfoBean infoBean = new ChapterInfoBean();
                                                                                if (!body.equals("")) {
                                                                                    infoBean.setBody(body);
                                                                                }
                                                                                chapterInfos.add(infoBean);
                                                                                titles.add(bookChapter.getTitle());
                                                                                String title = titles.poll();
                                                                                BookRepository.getInstance().saveChapterInfo(
                                                                                        bookId, title, infoBean.getBody()
                                                                                );
                                                                                i = 0;
                                                                                handler.post(runnableUis);
                                                                                break;
                                                                            } else {
                                                                                Thread.sleep(1000);
                                                                                i++;
                                                                            }
                                                                            if (i == 5) {
                                                                                handler.post(runnableUi);
                                                                                break;
                                                                            }

                                                                        }
                                                                    } catch (Exception e) {
                                                                        handler.post(runnableUi);
                                                                        e.printStackTrace();
                                                                    }
                                                                }
                                                            }).start();
                                                        }
                                                    } catch (Exception e1) {
                                                        e1.printStackTrace();
                                                    }
                                                }
                                            });
                                        } catch (Exception e) {
                                        }
                                    }

                                }
                            }
                        }

                        @Override
                        public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                            if (errorCode == -1) {
                                Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            } catch (Exception e) {
                e.printStackTrace();
                handler.post(runnableUi);
            }
    }

    private void getChapter(String url, String loadUrl, final int currentChapter) {
            try {
                mOkHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                        .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                        .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                        .retryOnConnectionFailure(true)             //是否自动重连
                        .build();
                final Request request = new Request.Builder()
                        .url(contentUrl)
                        .get()
                        .build();
                Call call = mOkHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("*********", "fail");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String str = response.body().string();
                        String headers[] = null;
                        Log.e("*************", str);
                        try {
                            JSONObject restr = JSONObject.parseObject(str);
                            if (restr.get("failed") != null) {
                                handler.post(runnableUi);
                            } else {
                                Message msg = new Message();
                                msg.obj = restr;
                                msg.what = 2;
                                handlers.sendMessage(msg);
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                });
            } catch (Exception e) {
                Log.e("*************", "异常");
            }

    }

    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            errorChapter();
        }

    };
    Runnable runnableUis = new Runnable() {
        @Override
        public void run() {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
            }
            finishChapter();
        }

    };
    Runnable ruUi = new Runnable() {
        @Override
        public void run() {
           mPageLoader.showTitle(chapterTitle);
        }

    };


    public boolean isEven01(int num) {
        if (num % 2 == 0) {
            return true;
        } else {
            return false;
        }
    }

    protected void processLogic() {
            if (getIntent().getStringExtra("goChapters") != null) {
                if (getIntent().getStringExtra("goChapters").equals("1")) {
                    bookId = getIntent().getStringExtra("bookId");
                    currentChapterLink = getIntent().getStringExtra("currentChapterLink");
                    currentChapter = Integer.parseInt(getIntent().getStringExtra("currentChapter"));
                    chapterTitle = getIntent().getStringExtra("title");
                    if (recommendBooks.getBookChapters() != null) {
                        nextChapterRead(bookId);
                    } else {
                        Disposable disposable = BookRepository.getInstance()
                                .getBookChaptersInRx(bookId)
                                .compose(RxUtils::toSimpleSingle)
                                .subscribe(
                                        (bookChapterBeen, throwable) -> {
                                            if (bookChapterBeen.size() > 0) {
                                                recommendBooks.setBookChapters(bookChapterBeen);
                                                nextChapterRead(bookId);
                                            }
                                        }
                                );
                        if (mDisposable == null) {
                            mDisposable = new CompositeDisposable();
                        }
                        mDisposable.add(disposable);
                    }
                } else {
                    BookMark mark = (BookMark) getIntent().getSerializableExtra("source");
                    mPageLoader.skipToChapter(mark.chapter);
                    hideReadBar();
                }

            } else {
                //如果是本地文件
                if (recommendBooks.isLocal()) {
                    mPageLoader.openBook(recommendBooks);
                } else {
                    //如果是已经收藏的，那么就从数据库中获取目录
                    Disposable disposable = BookRepository.getInstance()
                            .getBookChaptersInRx(bookId)
                            .compose(RxUtils::toSimpleSingle)
                            .subscribe(
                                    (bookChapterBeen, throwable) -> {
                                        if (bookChapterBeen != null) {
                                            recommendBooks.setBookChapters(bookChapterBeen);
                                            mChapterList.addAll(bookChapterBeen);
                                            mPageLoader.openBook(recommendBooks);
                                        } else {
                                            handler.post(runnableUi);
                                        }

                                    }
                            );
                    addDisposable(disposable);
                }
            }

    }

    protected void addDisposable(Disposable d) {
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(d);
        initClick();
    }

    public void showCategory(List<BookChapterBean> bookChapters) {
        hideDialog();
        recommendBooks.setBookChapters(bookChapters);
        //如果是更新加载，那么重置PageLoader的Chapter
        if (recommendBooks.isUpdate() && isFromSD) {
            mPageLoader.setChapterList(bookChapters);
            BookRepository.getInstance()
                    .saveBookChaptersWithAsync(bookChapters);
        } else {
            mPageLoader.openBook(recommendBooks);
        }
    }

    protected void initClick() {
        mPageLoader.setOnPageChangeListener(
                new PageLoader.OnPageChangeListener() {
                    @Override
                    public void onChapterChange(int pos) {

                    }

                    @Override
                    public void onLoadChapter(List<TxtChapter> chapters, int pos) {
                        loadChapter(bookId, chapters);

                        if (mPageLoader.getPageStatus() == NetPageLoader.STATUS_LOADING
                                || mPageLoader.getPageStatus() == NetPageLoader.STATUS_ERROR) {

                        }
                    }

                    @Override
                    public void onCategoryFinish(List<TxtChapter> chapters) {

                    }

                    @Override
                    public void onPageCountChange(int count) {

                    }

                    @Override
                    public void onPageLastChange() {

                    }

                    @Override
                    public void onPageChange(int pos) {
                        if(pos==0){
                            if(!(SharedPreferencesUtil.getInstance().getString("perChapterStart")==null||SharedPreferencesUtil.getInstance().getString("perChapterStart").equals(""))){
                                if(SharedPreferencesUtil.getInstance().getString("perChapterStart").equals("true")){
                                    if(adLayout.getVisibility()==View.VISIBLE){
                                        adLayout.setVisibility(View.VISIBLE);
                                    }else {
                                        mill_layout.removeAllViews();
                                        DRAgent.getInstance().getOpenView(mContext, ADType.FULL_SCREEN, false, new IAdSuccessBack() {

                                            @Override
                                            public void onError(final String result) {

                                            }

                                            @Override
                                            public void onClick(String result) {
                                                // TODO Auto-generated method stub
                                                // TODO Auto-generated method stub

                                            }

                                            @Override
                                            public void OnSuccess(String result) {
                                                // TODO Auto-generated method stub

                                                // TODO Auto-generated method stub


                                            }

                                            @Override
                                            public void OnLoadAd(View view) {
                                                // TODO Auto-generated method stub
                                                System.out.println(">>>>>>广告加载成功");
                                                adLayout.setVisibility(View.VISIBLE);
                                                mill_layout.addView(view);
                                            }
                                        });
                                    }
                                }else{
                                    adLayout.setVisibility(View.GONE);
                                }
                            }else {
                                mill_layout.removeAllViews();
                                DRAgent.getInstance().getOpenView(mContext, ADType.MESSAGE_BIG_IMG, true, new IAdSuccessBack() {

                                    @Override
                                    public void onError(final String result) {

                                    }

                                    @Override
                                    public void onClick(String result) {
                                        // TODO Auto-generated method stub
                                        // TODO Auto-generated method stub

                                    }

                                    @Override
                                    public void OnSuccess(String result) {
                                        // TODO Auto-generated method stub

                                        // TODO Auto-generated method stub
                                        if (result.equals("7")) {
                                            adLayout.setVisibility(View.GONE);
                                        }

                                    }

                                    @Override
                                    public void OnLoadAd(View view) {
                                        // TODO Auto-generated method stub
                                        System.out.println(">>>>>>广告加载成功");
                                        adLayout.setVisibility(View.VISIBLE);
                                        mill_layout.addView(view);
                                    }
                                });
                            }
                            if (!(SharedPreferencesUtil.getInstance().getString("chapterBottom") == null || SharedPreferencesUtil.getInstance().getString("chapterBottom").equals(""))) {

                                if (SharedPreferencesUtil.getInstance().getString("chapterBottom").equals("true")) {
                                        DRAgent.getInstance().getOpenNativeAd(ReadActivity.this, ADType.MESSAGE_BIG_IMG, new IAdNativeSuccessBack() {
                                            @Override
                                            public void onSuccess(final Advertisement advertisement) {
                                                // TODO Auto-generated method stub
                                                System.out.println(">>>>>>>>>>>>原生广告信息:" + advertisement.toString());
                                                Message msg=new Message();
                                                msg.obj=advertisement;
                                                handlerss.sendMessage(msg);
                                            }

                                            @Override
                                            public void onFailed(String infoStr) {
                                                // TODO Auto-generated method stub
                                                System.out.println(">>>>>>>>>>infoStr:"+infoStr);

                                            }
                                        });
//                                        DRAgent.getInstance().getOpenView(mContext, ADType.MESSAGE_IMGS, true, new IAdSuccessBack() {
//
//                                            @Override
//                                            public void onError(final String result) {
//
//                                            }
//
//                                            @Override
//                                            public void onClick(String result) {
//                                                // TODO Auto-generated method stub
//                                                // TODO Auto-generated method stub
//
//                                            }
//
//                                            @Override
//                                            public void OnSuccess(String result) {
//                                                // TODO Auto-generated method stub
//
//                                                // TODO Auto-generated method stub
//
//                                            }
//
//                                            @Override
//                                            public void OnLoadAd(View view) {
//                                                // TODO Auto-generated method stub
//                                                adBooTomLayout.setVisibility(View.VISIBLE);
//                                                bannerLayout.addView(view);
//                                            }
//                                        });
                                }else{
                                    adBooTomLayout.setVisibility(View.GONE);
                                }
                            }else{
                                DRAgent.getInstance().getOpenNativeAd(ReadActivity.this, ADType.MESSAGE_BIG_IMG, new IAdNativeSuccessBack() {
                                    @Override
                                    public void onSuccess(final Advertisement advertisement) {
                                        // TODO Auto-generated method stub
                                        System.out.println(">>>>>>>>>>>>原生广告信息:" + advertisement.toString());
                                        Message msg=new Message();
                                        msg.obj=advertisement;
                                        handlerss.sendMessage(msg);
                                    }

                                    @Override
                                    public void onFailed(String infoStr) {
                                        // TODO Auto-generated method stub
                                        System.out.println(">>>>>>>>>>infoStr:"+infoStr);

                                    }
                                });
                            }
                        }
                    }
                }
        );
        mPvPage.setTouchListener(new PageView.TouchListener() {
            @Override
            public void center() {
                toggleMenu(true);
            }
            @Override
            public boolean onTouch() {

                    BookRecordBean mBookRecords = BookRepository.getInstance()
                            .getBookRecord(bookId);
                    BookMark mark = new BookMark();
                    mark.desc = mPageLoader.getHeadLine();
                    if (mBookRecords != null) {
                        mark.chapter = mBookRecords.getChapter();
                        mark.startPos = mBookRecords.getPagePos();
                        if (mark.chapter >= 1 && mark.chapter <= mChapterList.size()) {
                            mark.title = mChapterList.get(mark.chapter).getTitle();
                        }
                    }
                    if (SettingManager.getInstance().ifBookMark(bookId, mark)) {
                        Drawable drawable = ContextCompat.getDrawable(mContext, R.mipmap.ic_menu_bookmark);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        tvBookMark.setCompoundDrawables(drawable, null, null, null);
                    } else {
                        Drawable drawable = ContextCompat.getDrawable(mContext, R.mipmap.ic_mark_hover);
                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                        tvBookMark.setCompoundDrawables(drawable, null, null, null);
                    }

                    return !hideReadMenu();
            }
            @Override
            public boolean prePage() {
                mTvDownloadProgress.setVisibility(View.GONE);
                rlReadAaSet.setVisibility(View.GONE);
                mLlBookReadBottom.setVisibility(View.GONE);
                return !hideReadMenu();
            }

            @Override
            public boolean nextPage() {
                mTvDownloadProgress.setVisibility(View.GONE);
                rlReadAaSet.setVisibility(View.GONE);
                mLlBookReadBottom.setVisibility(View.GONE);
                return !hideReadMenu();
            }

            @Override
            public void cancel() {

            }
        });
    }

    /**
     * 切换菜单栏的可视状态
     * 默认是隐藏的
     */
    private void toggleMenu(boolean hideStatusBar) {
        if (mLlBookReadTop.getVisibility() == View.VISIBLE) {
            //关闭
            mTvDownloadProgress.setVisibility(View.GONE);
            rlReadAaSet.setVisibility(View.GONE);
            mLlBookReadBottom.setVisibility(View.GONE);
            mLlBookReadTop.setVisibility(View.GONE);
        } else {
            mTvDownloadProgress.setVisibility(View.GONE);
            rlReadAaSet.setVisibility(View.GONE);
            mLlBookReadBottom.setVisibility(View.VISIBLE);
            mLlBookReadTop.setVisibility(View.VISIBLE);
        }
    }

    private void setMenu(boolean hideStatusBar) {
        if (mLlBookReadTop.getVisibility() == View.VISIBLE) {
            //关闭
            mTvDownloadProgress.setVisibility(View.GONE);
            rlReadAaSet.setVisibility(View.VISIBLE);
            mLlBookReadBottom.setVisibility(View.VISIBLE);
            mLlBookReadTop.setVisibility(View.GONE);
        } else {
            mTvDownloadProgress.setVisibility(View.GONE);
            rlReadAaSet.setVisibility(View.GONE);
            mLlBookReadBottom.setVisibility(View.GONE);
            mLlBookReadTop.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏阅读界面的菜单显示
     *
     * @return 是否隐藏成功
     */
    private boolean hideReadMenu() {
        if (mLlBookReadTop.getVisibility() == VISIBLE) {
            toggleMenu(true);
            return true;
        }
        return false;
    }


    public void loadChapter(String bookId, List<TxtChapter> bookChapters) {
        Message message = new Message();
        message.what = 1;
        message.obj = bookChapters;
        handlers.sendMessage(message);

    }

    public void finishChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {

            mPageLoader.openChapter();
            chapterTitle="";
        }

    }

    public void errorChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mPageLoader.chapterError();
            chapterTitle="";
        }
    }
    public void emptyChapter() {
        if (mPageLoader.getPageStatus() == PageLoader.STATUS_LOADING) {
            mPageLoader.chapterEmpty();
        }
    }
    Handler handlers = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    List<TxtChapter> bookChapters = (List<TxtChapter>) msg.obj;
                    int size = bookChapters.size();
                    //取消上次的任务，防止多次加载
                    if (mChapterSub != null) {
                        mChapterSub.cancel();
                    }
                    List<Single<ChapterInfoBean>> chapterInfo = new ArrayList<>(bookChapters.size());
                    ArrayDeque<String> titleList = new ArrayDeque<>(bookChapters.size());
                    //首先判断是否Chapter已经存在
                    for (int i = 0; i < size; ++i) {
                        TxtChapter bookChapter = bookChapters.get(i);
                        if (!(BookManager
                                .isChapterCached(bookId, bookChapter.getTitle()))) {
                            //网络中获取数据
                            getChapterRead(bookId, bookChapters, bookChapter);

                        }
                        //如果已经存在，再判断是不是我们需要的下一个章节，如果是才返回加载成功
                        else if (i == 0) {
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            handler.post(runnableUis);
                        }
                    }
                    Single.concat(chapterInfo)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(
                                    new Subscriber<ChapterInfoBean>() {
                                        String title = titleList.poll();

                                        @Override
                                        public void onSubscribe(Subscription s) {
                                            s.request(Integer.MAX_VALUE);
                                            mChapterSub = s;
                                        }

                                        @Override
                                        public void onNext(ChapterInfoBean chapterInfoBean) {
                                            //存储数据
                                            BookRepository.getInstance().saveChapterInfo(
                                                    bookId, title, chapterInfoBean.getBody()
                                            );
                                            handler.post(runnableUis);
                                            //将获取到的数据进行存储
                                            title = titleList.poll();

                                        }

                                        @Override
                                        public void onError(Throwable t) {
                                            //只有第一个加载失败才会调用errorChapter
                                            if (bookChapters.get(0).getTitle().equals(title)) {

                                            }
                                            LogUtils.e(t);
                                        }

                                        @Override
                                        public void onComplete() {
                                        }
                                    }
                            );

                    break;
                case 2:
                    try {
                        JSONObject restr = (JSONObject) msg.obj;
                        helper = new SiteHelper(restr);

                        String loadUrls;
                        if (loadUrl.indexOf("https") != -1) {
                            loadUrls = loadUrl;
                        } else {
                            if (loadUrl.indexOf("qidian.com") != -1) {
                                loadUrls = loadUrl.replace("http", "https");
                            } else {
                                loadUrls = loadUrl;
                            }
                        }
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                     Map<String, Object> contexts = new HashMap<String, Object>();
                                    contexts.put("aid", aid);
                                    contexts = helper.executeMulu(contexts, loadUrls);
                                    int i = 0;
                                    while (true) {
                                        Object[] chapters = (Object[]) contexts.get("chapters");//因目录获取经常不到，故循环获取
                                        if (chapters != null) {
                                            hideDialog();
                                            mChapterList.clear();
                                            for (Object o : chapters) {
                                                JSONObject cJson = (JSONObject) o;
                                                if (!cJson.getString("vip").equals("true")) {
                                                    BookChapterBean chapterBean = new BookChapterBean();
                                                    chapterBean.setBookId(bookId);
                                                    chapterBean.setLink(cJson.getString("url"));
                                                    chapterBean.setTitle(cJson.getString("name"));
                                                    mChapterList.add(chapterBean);
                                                }
                                            }
                                            BookRepository.getInstance()
                                                    .saveBookChaptersWithAsync(mChapterList);
                                            SitBean sitBean=new SitBean();
                                            sitBean.setId(bookId);
                                            sitBean.setUrl(contentUrl);
                                            sitBean.setLoadUrl(loadUrl);
                                            SitRepository.getInstance().saveSit(sitBean);
                                            break;
                                        }else{
                                            Thread.sleep(1000);
                                            i++;
                                        }
                                        if (i > 8) {
                                            hideDialog();
                                            handler.post(runnableUi);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 3:

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                TxtChapter bookChapter = (TxtChapter) msg.obj;
                                Map<String, Object> context2 = new HashMap<String, Object>();
                                context2.put("aid", aid);
                                context2 = helper.executeChapter(context2, bookChapter.getLink());
                                int i = 0;
                                while (true) {
                                    i++;
                                    Object content = (String) context2.get("content");
                                    String body = "";
                                    if (content != null) {
                                        if (content.getClass() == JSONObject.class) {
                                            JSONObject contentJson = (JSONObject) content;
                                            body = contentJson.getString("text");
                                        } else {
                                            body = content.toString();
                                        }
                                        ChapterInfoBean infoBean = new ChapterInfoBean();
                                        if (!body.equals("")) {
                                            infoBean.setBody(body);
                                        }
                                        chapterInfos.add(infoBean);
                                        titles.add(bookChapter.getTitle());
                                        String title = titles.poll();
                                        BookRepository.getInstance().saveChapterInfo(
                                                bookId, title, infoBean.getBody()
                                        );
                                        i = 0;
                                        handler.post(runnableUis);
                                        break;
                                    }else{
                                        Thread.sleep(1000);
                                        i++;
                                    }
                                    if (i == 5) {
                                        handler.post(runnableUi);
                                        break;
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (mProgressDialog != null) {
                                    mProgressDialog.dismiss();
                                }
                            }
                        }
                    }).start();
                    break;
                case 4:
                    Map<String, Object> contexts = (Map<String, Object>) msg.obj;
                    while (true) {
                        Object[] chapters = (Object[]) contexts.get("chapters");//因目录获取经常不到，故循环获取
                        if (chapters != null) {
                            mChapterList.clear();
                            for (Object o : chapters) {
                                JSONObject cJson = (JSONObject) o;
                                if (!cJson.getString("vip").equals("true")) {
                                    BookChapterBean chapterBean = new BookChapterBean();
                                    chapterBean.setBookId(bookId);
                                    chapterBean.setLink(cJson.getString("url"));
                                    chapterBean.setTitle(cJson.getString("name"));
                                    mChapterList.add(chapterBean);
                                }
                            }
                            showCategory(mChapterList);
                            break;
                        }
                    }
                    break;
                case 5:
                    try {
                        String bookChapterLink = (String) msg.obj;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Map<String, Object> context2 = new HashMap<String, Object>();
                                    context2.put("aid", aid);
                                    context2 = helper.executeChapter(context2, bookChapterLink);
                                    int i = 0;
                                    while (true) {
                                        String body = "";
                                        if (context2.get("content") != null) {
                                            if (context2.get("content").getClass() == JSONObject.class) {
                                                JSONObject contentJson = (JSONObject) context2.get("content");
                                                body = contentJson.getString("text");
                                            } else {
                                                Object content = (String) context2.get("content");
                                                body = content.toString();
                                            }
                                            ChapterInfoBean infoBean = new ChapterInfoBean();
                                            if (!body.equals("")) {
                                                infoBean.setBody(body);
                                            }
                                            BookRepository.getInstance().saveChapterInfo(
                                                    bookId, chapterTitle, infoBean.getBody()
                                            );
                                            i=0;
                                            mPageLoader.openBook(recommendBooks);
                                            mPageLoader.skipToChapter(currentChapter);
                                            break;
                                        }else{
                                            Thread.sleep(1000);
                                            i++;
                                        }
                                        if (i == 5) {
                                            mPageLoader.openBook(recommendBooks);
                                            mPageLoader.skipToChapter(currentChapter);
                                            handler.post(runnableUi);
                                            break;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    handler.post(runnableUi);
                                }
                            }
                        }).start();


                    } catch (Exception e) {
                        e.printStackTrace();
                        handler.post(runnableUi);
                    }
                    break;
                case 7:
                    BrightnessUtils.startAutoBrightness(ReadActivity.this);
                    BrightnessUtils.setBrightness(ReadActivity.this, BrightnessUtils.getScreenBrightness(ReadActivity.this));
                    break;
                case 8:
                    BrightnessUtils.stopAutoBrightness(ReadActivity.this);
                    BrightnessUtils.setBrightness(ReadActivity.this, seekbarLightness.getProgress());
                    break;
            }
        }
    };

    public void nextChapterRead(String bookId) {

            try {
                Map<String, Object> context2 = new HashMap<String, Object>();
                context2.put("aid", aid);
                BookReadService.getBookMixAToc(mContext, bookId, new ResponseCallback<BookSit>() {
                    @Override
                    public void onSuccess(BookSit mixToc) {
                        if (mixToc != null) {
                            List<BookSit.Chapters> list = mixToc.mulus;
                            mChapterSitList.clear();
                            if (list != null) {
                                mChapterSitList.addAll(list);

                                if (mChapterSitList.size() > 0) {

                                    contentUrl =bean.getUrl();
                                    try {
                                        mOkHttpClient = new OkHttpClient.Builder()
                                                .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                                .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                                .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                                .retryOnConnectionFailure(true)             //是否自动重连
                                                .build();
                                        final Request request = new Request.Builder()
                                                .url(contentUrl)
                                                .get()
                                                .build();
                                        Call call = mOkHttpClient.newCall(request);
                                        call.enqueue(new Callback() {
                                            @Override
                                            public void onFailure(Call call, IOException e) {

                                            }

                                            @Override
                                            public void onResponse(Call call, Response response) throws IOException {
                                                String str = response.body().string();
                                                String headers[] = null;
                                                try {
                                                    JSONObject restr = JSONObject.parseObject(str);
                                                    if (restr.get("failed") != null) {
                                                        handler.post(runnableUi);
                                                    } else {
                                                        helper = new SiteHelper(restr);
                                                        Map<String, Object> context2 = new HashMap<String, Object>();
                                                        context2.put("aid", aid);
                                                        Message message = new Message();
                                                        message.what = 5;
                                                        message.obj = currentChapterLink;
                                                        handlers.sendMessage(message);
                                                    }
                                                } catch (Exception e1) {
                                                    e1.printStackTrace();
                                                }
                                            }
                                        });
                                    } catch (Exception e) {
                                    }
                                    //getChapter(mChapterSitList.get(0).domain,contentUrl, currentChapter);
                                }

                            }
                        }
                    }

                    @Override
                    public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                       // Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                handler.post(runnableUi);
            }

    }

    @Override
    protected void onResume() {
        super.onResume();
        mWakeLock.acquire();
        MobclickAgent.onPageStart("阅读页");
        MobclickAgent.onResume(context);
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerBrightObserver();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mWakeLock.release();
        if (isFromSD){
            mPageLoader.saveRecord();
        }
        MobclickAgent.onPageEnd("阅读页");
        MobclickAgent.onPause(context);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterBrightObserver();
    }
    //注册亮度观察者
    private void registerBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (!isRegistered) {
                    final ContentResolver cr = getContentResolver();
                    cr.unregisterContentObserver(mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_URI, false, mBrightObserver);
                    cr.registerContentObserver(BRIGHTNESS_ADJ_URI, false, mBrightObserver);
                    isRegistered = true;
                }
            }
        } catch (Throwable throwable) {

        }
    }

    //解注册
    private void unregisterBrightObserver() {
        try {
            if (mBrightObserver != null) {
                if (isRegistered) {
                    getContentResolver().unregisterContentObserver(mBrightObserver);
                    isRegistered = false;
                }
            }
        } catch (Throwable throwable) {

        }
    }


    Handler handlerss = new Handler() {
        public void handleMessage(android.os.Message msg){
            adBooTomLayout.setVisibility(View.VISIBLE);
            advertisement=(Advertisement) msg.obj;
            if(advertisement!=null) {
                GlideLoadUtils.getInstance().glideLoad(ReadActivity.this, advertisement.getImgurl(), iv_ad_image, R.mipmap.cover_default);
                if (advertisement.getWenzi() != null) {
                    adText.setText(advertisement.getWenzi());
                }
                DRAgent.getInstance().uploadShow(ReadActivity.this, advertisement);
            }
        };
    };

    public void getHitHelper(){
        BookReadService.getBookMixAToc(mContext, bookId, new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                tips.setVisibility(View.GONE);
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;
                    mChapterSitList.clear();
                    if (list != null) {
                        mChapterSitList.addAll(list);

                        if (mChapterSitList.size() > 0) {
                            contentUrl =bean.getUrl();
                            try {
                                mOkHttpClient = new OkHttpClient.Builder()
                                        .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                                        .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                                        .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                                        .retryOnConnectionFailure(true)             //是否自动重连
                                        .build();
                                final Request request = new Request.Builder()
                                        .url(contentUrl)
                                        .get()
                                        .build();
                                Call call = mOkHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {

                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String str = response.body().string();
                                        String headers[] = null;
                                        try {
                                            JSONObject restr = JSONObject.parseObject(str);
                                            if (restr.get("failed") != null) {
                                                handler.post(runnableUi);
                                            } else {
                                                helper = new SiteHelper(restr);
                                            }
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                        }
                                    }
                                });
                            } catch (Exception e) {
                            }
                        }

                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                if (errorCode == -1) {
                    Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}
